﻿using Xejen.Communication.Socket.Abstract;
using Xejen.Communication.Socket.Communicator;
using Xejen.Hosting.Extensions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

namespace Xejen.Communication.Socket.Extensions
{
    /// <summary>
    /// 针对<see cref="ISocketCommunicatorBuilder"/>进行扩展
    /// </summary>
    /// <creator>marc</creator>
    public static class SocketCommunicatorBuilderExtensions
    {
        /// <summary>
        /// 添加Socket通讯器
        /// </summary>
        /// <returns></returns>
        public static ISocketCommunicatorBuilder AddCommunicator(this ISocketCommunicatorBuilder builder)
        {
            var logger = builder.LoggerManager.CreateLogger(typeof(SocketCommunicatorBuilderExtensions));
            builder.Host.AddServices((services) =>
            {
                foreach (var connection in builder.Config.Connections)
                {
                    services.AddSingleton<ISocketCommunicator>(sp =>
                    {
                        ISocketInvokerCreator<TcpInvoker> invoker = new TcpInvokerCreator();
                        SocketCommunicator<TcpInvoker> communicator = new SocketCommunicator<TcpInvoker>(builder.Config, invoker, builder.LoggerManager);
                        communicator.SetCurrentConnection(connection);
                        return communicator;
                    });
                }
            });
            logger.LogInformation($"完成Socket通讯器构建");
            return builder;
        }
    }
}
